/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 应用路由管理器
 */

import 'package:flutter/material.dart';
import '../pages/music_search_page.dart';
import '../pages/music_player_page.dart';
import '../pages/playlist_page_view.dart';

/// 应用路由管理器
class AppRoutes {
  /// 路由名称常量
  static const String home = '/';
  static const String musicSearch = '/music_search';
  static const String musicPlayer = '/music_player';
  static const String playlist = '/playlist';

  /// 路由映射表
  static Map<String, WidgetBuilder> get routes => {
        musicSearch: (context) => const MusicSearchPage(),
        musicPlayer: (context) => const MusicPlayerPage(),
        playlist: (context) => const PlaylistPageView(),
      };

  /// 路由生成器（用于处理动态路由）
  static Route<dynamic>? onGenerateRoute(RouteSettings settings) {
    switch (settings.name) {
      case musicPlayer:
        // 可以传递参数给播放页面
        final args = settings.arguments as Map<String, dynamic>?;
        return MaterialPageRoute(
          builder: (context) => MusicPlayerPage(
            initialMusic: args?['music'],
            autoPlay: args?['autoPlay'] ?? false,
          ),
        );

      case playlist:
        // 可以传递初始索引给播放列表页面
        final args = settings.arguments as Map<String, dynamic>?;
        return MaterialPageRoute(
          builder: (context) => PlaylistPageView(
            initialIndex: args?['initialIndex'] ?? 0,
          ),
        );

      default:
        return null;
    }
  }

  /// 导航到音乐搜索页面
  static Future<void> toMusicSearch(BuildContext context) {
    return Navigator.pushNamed(context, musicSearch);
  }

  /// 导航到音乐播放页面
  static Future<void> toMusicPlayer(
    BuildContext context, {
    dynamic music,
    bool autoPlay = false,
  }) {
    return Navigator.pushNamed(
      context,
      musicPlayer,
      arguments: {
        'music': music,
        'autoPlay': autoPlay,
      },
    );
  }

  /// 导航到播放列表页面
  static Future<void> toPlaylist(
    BuildContext context, {
    int initialIndex = 0,
  }) {
    return Navigator.pushNamed(
      context,
      playlist,
      arguments: {
        'initialIndex': initialIndex,
      },
    );
  }

  /// 返回上一页
  static void back(BuildContext context) {
    Navigator.of(context).pop();
  }

  /// 返回到首页
  static void backToHome(BuildContext context) {
    Navigator.of(context).popUntil((route) => route.isFirst);
  }

  /// 替换当前页面
  static Future<void> replace(BuildContext context, String routeName,
      {Object? arguments}) {
    return Navigator.pushReplacementNamed(
      context,
      routeName,
      arguments: arguments,
    );
  }

  /// 清空栈并导航到指定页面
  static Future<void> pushAndClearStack(
    BuildContext context,
    String routeName, {
    Object? arguments,
  }) {
    return Navigator.pushNamedAndRemoveUntil(
      context,
      routeName,
      (route) => false,
      arguments: arguments,
    );
  }
}
